using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.property;
using umbraco;
using umbraco.BusinessLogic;
using umbraco.BusinessLogic.console;
using System.Xml;
using System.IO;

namespace TG.Umb.DateFolder
{
    public partial class DateFolderInstall : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
                DocumentType temp = DocumentType.GetByAlias("DateFolder");
                
                foreach (DocumentType all in DocumentType.GetAll)
                {
                    if(all.Alias != "DateFolder")
                    {
                        CheckBox tempc = new CheckBox();
                        tempc.ID = all.Alias;
                        tempc.Text = all.Alias;
                        tempc.AutoPostBack = true;
                        tempc.CheckedChanged += new EventHandler(box_CheckedChanged);
                        Panel3.Controls.Add(tempc);
                        Literal lit = new Literal();
                        lit.Text = "<br/>";

                        Panel3.Controls.Add(lit);
                    }
                }
            
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //Label1.Text = "";

            DocumentType datefolder = DocumentType.GetByAlias("DateFolder");

           
            if (Session["DateFolderInstall"] != null)
            {
                for( int i=0; i < ((ArrayList)Session["DateFolderInstall"]).Count; i++)
                {
                   

                    string alias = ((ArrayList)Session["DateFolderInstall"])[i].ToString();
                    

                    DocumentType currentDocType = DocumentType.GetByAlias(alias);

                    // allow datefolder to have childnode of currentDoctype

                    bool add = true;
                    int[] newArray;
                    newArray = new int[datefolder.AllowedChildContentTypeIDs.Length + 1];

                    for (int j = 0; j < datefolder.AllowedChildContentTypeIDs.Length; j++)
                    {
                        
                        newArray[j] = (int) datefolder.AllowedChildContentTypeIDs.GetValue(j);

                        if ((int)datefolder.AllowedChildContentTypeIDs.GetValue(j) == currentDocType.Id)
                        {
                            add = false;
                        }

                    }

                    newArray[datefolder.AllowedChildContentTypeIDs.Length] = currentDocType.Id;

                    if (add)
                    {
                        datefolder.AllowedChildContentTypeIDs = newArray;
                    }

                    //


                    // find parent 
                    foreach (DocumentType parentDoc in DocumentType.GetAll)
                    {
                        foreach (int childDocType in parentDoc.AllowedChildContentTypeIDs)
                        {
                            if (childDocType == currentDocType.Id)
                            {
                                if (parentDoc.Alias != "DateFolder")
                                {
                                    // allow parendDoctype to allow datafolder doctypes
                                    //Label1.Text += "allow for " + parentDoc.Alias + "<br/>";

                                    bool addParent = true;
                                    int[] newArrayParent;
                                    newArrayParent = new int[parentDoc.AllowedChildContentTypeIDs.Length + 1];

                                    for (int j = 0; j < parentDoc.AllowedChildContentTypeIDs.Length; j++)
                                    {

                                        newArrayParent[j] = (int)parentDoc.AllowedChildContentTypeIDs.GetValue(j);

                                        if ((int)parentDoc.AllowedChildContentTypeIDs.GetValue(j) == datefolder.Id)
                                        {
                                            addParent = false;
                                        }

                                    }

                                    newArrayParent[parentDoc.AllowedChildContentTypeIDs.Length] = datefolder.Id;

                                    if (addParent)
                                    {
                                        parentDoc.AllowedChildContentTypeIDs = newArrayParent;
                                    }

                                }
                            }

                        }
                    }
                   
                       
                    
                    // add to config
                    XmlDocument xd = new XmlDocument();
                    xd.Load(HttpContext.Current.Server.MapPath("/config/TG.Umb.DateFolder/DateFolder.config"));

                   

                    xd.SelectSingleNode("DateFolder").AppendChild(xmlHelper.addTextNode(xd, "DocumentTypeAlias", alias));

                    FileStream stream = File.Open(HttpContext.Current.Server.MapPath("/config/TG.Umb.DateFolder/DateFolder.config"), FileMode.Create);
                    StreamWriter writer = new StreamWriter(stream);
                    writer.WriteLine(xd.OuterXml);
                    writer.Close();
                    stream.Close();



                    //check move
                    if (cbMove.Checked)
                    {
                        // move

                        foreach (Document root in Document.GetRootDocuments())
                        {
                           
                            if (root.HasChildren)
                            {
                                loopchildren(root, alias);
                            }
                        }
                        
                    }
                        
                }

                Panel1.Visible = false;
                Panel2.Visible = true;
            }


        }

        private void loopchildren(Document ParentDocument, string alias)
        {
          
            
            foreach (Document tempDocument in ParentDocument.Children)
            {
                
                if (tempDocument.Id > 0)
                {
                    if (tempDocument.ContentType.Alias == alias)
                    {

                         Move(tempDocument);
                        
                    }

                    if (tempDocument.HasChildren)
                    {
                        loopchildren(tempDocument, alias);
                    }
                }
            }
           
        }

        private void Move(Document documentObject)
        {
            if (new Document(documentObject.Parent.Id).ContentType.Alias != "DateFolder")
            {



                string[] strArray = (documentObject.CreateDateTime.Year.ToString() + "-" + documentObject.CreateDateTime.Month.ToString() + "-" + documentObject.CreateDateTime.Day.ToString()).Split("-".ToCharArray());
                if (strArray.Length == 3)
                {
                    Document document = null;
                    foreach (IconI ni in documentObject.Parent.Children)
                    {
                        if (ni.Text == strArray[0])
                        {
                            document = new Document(ni.Id);
                            break;
                        }
                    }
                    if (document == null)
                    {
                        document = Document.MakeNew(strArray[0], DocumentType.GetByAlias("DateFolder"), documentObject.User, documentObject.Parent.Id);
                        document.Publish(documentObject.User);
                        library.PublishSingleNode(document.Id);
                    }
                    else
                    {

                        Log.Add(LogTypes.Debug, documentObject.User, documentObject.Id, "executed - year not null");
                    }
                    Document document2 = null;
                    Document[] children = document.Children;
                    for (int i = 0; i < children.Length; i++)
                    {
                        IconI ni2 = children[i];
                        if (ni2.Text == strArray[1])
                        {
                            document2 = new Document(ni2.Id);
                            break;
                        }
                    }
                    if (document2 == null)
                    {
                        document2 = Document.MakeNew(strArray[1], DocumentType.GetByAlias("DateFolder"), documentObject.User, document.Id);
                        document2.Publish(documentObject.User);
                        library.PublishSingleNode(document2.Id);
                    }
                    Document document3 = null;
                    Document[] documentArray2 = document2.Children;
                    for (int j = 0; j < documentArray2.Length; j++)
                    {
                        IconI ni3 = documentArray2[j];
                        if (ni3.Text == strArray[2])
                        {
                            document3 = new Document(ni3.Id);
                            break;
                        }
                    }
                    if (document3 == null)
                    {
                        document3 = Document.MakeNew(strArray[2], DocumentType.GetByAlias("DateFolder"), documentObject.User, document2.Id);
                        document3.Publish(documentObject.User);
                        library.PublishSingleNode(document3.Id);
                    }
                    documentObject.Move(document3.Id);

                }
            }

        }

        protected void box_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox current = (CheckBox)sender;

            if (Session["DateFolderInstall"] == null)
            {
                ArrayList checkedboxes = new ArrayList();
                if (current.Checked)
                {
                    checkedboxes.Add(current.Text);
                }
                else
                {
                    checkedboxes.Remove(current.Text); 
                }

                Session["DateFolderInstall"] = checkedboxes;
            }
            else
            {
                if (current.Checked)
                {
                    ((ArrayList)Session["DateFolderInstall"]).Add(current.Text);
                }
                else
                {
                    ((ArrayList)Session["DateFolderInstall"]).Remove(current.Text);
                }

                
            }

        }
    }
}